package com.phospherus.flow.service;

import com.phospherus.common.AttachedFile;
import com.phospherus.common.service.IAttachedFileService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author songjinlong
 * @version 1.0
 * @since 2017/12/21
 */
public abstract class FormInstBaseService {
    public static final Map<String, FormInstBaseService> SERVICE_MAP = new HashMap<>();

    {
        SERVICE_MAP.put(this.getFormInstServiceName(), this);
    }

    @Autowired
    protected IAttachedFileService attachedFileService;

    abstract String getFormInstServiceName();

    /**
     * 保存表单数据
     *
     * @param map
     * @return
     */
    abstract void save(Map<String, Object> map);

    abstract Map<String, Object> query(Long formInstId);

    protected <T> T createEntityByMap(Map<String, Object> map, Class destClass) throws IllegalAccessException, InstantiationException {

        T t = (T) destClass.newInstance();
        Field[] fields = destClass.getDeclaredFields();
        for (Field field : fields) {
            if (field.getName().equals("createTime") || field.getName().equals("modifyTime")) {
                continue;
            }
            field.setAccessible(true);
            Object value = map.get(field.getName());
            if(value==null){
                continue;
            }
            if (field.getType() == Long.class) {
                String vStr = value.toString();
                if (StringUtils.isBlank(vStr)) {
                    continue;
                }
                value = Long.parseLong(vStr);
            }
            field.set(t, value);
            field.setAccessible(false);
        }
        return t;
    }
}
